import hashlib
import logging
import os
import sys

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

from model import *
from util import *

class SeedHoffman(webapp.RequestHandler):
    """
    Implement the "Hoffman-style" bittorrent file-fetching-from-the-web protocol.
    See http://www.bittorrent.org/beps/bep_0017.html for specs.
    """

    def compute_data(self, data, ranges):  # internal helper
        # URL request looks like: ranges=49152-131071,180224-262143
        if ranges is None:
            return data
        result = ""
        for range in ranges.split(","):
            (start,end) = range.split("-")
            start = int(start); end = int(end)
            result += data[start:end+1]  # Ranges are inclusive
        return result

    def get(self):  # Serve up pieces as requested:
        info_hash_raw = GetParam("info_hash")
        pieceNumber = self.request.get("piece", default_value=None)
        ranges = self.request.get("ranges", default_value=None)
        if info_hash_raw is None or pieceNumber is None:
            self.error(400) # Bad Request
        info_hash = info_hash_raw.encode('hex_codec')
        pieceNumber = int(pieceNumber)
        t = Torrent.get_by_hash(info_hash)
        if t is None:
            self.error(400) # Bad Request
            return
        data = t.get_piece(pieceNumber)
        if data is None:
            self.error(404) # Not Found
            return
        self.response.headers["Content-Type"] = "application/octet-stream"
        self.response.out.write(self.compute_data(data, ranges))

application = webapp.WSGIApplication(
    [
      (r'.*', SeedHoffman)
    ],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
